package com.hbnu.system.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.WorkfileMapper;
import com.hbnu.system.model.entity.Work;
import com.hbnu.system.model.entity.Workfile;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.service.IWorkService;
import com.hbnu.system.service.IWorkfileService;
import com.hbnu.system.utils.CheckRoleUtil;
import com.hbnu.system.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.BindException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * (Workfile)表服务实现类
 *
 * @author makejava
 * @since 2023-10-14 16:19:30
 */
@Service("workfileService")
public class WorkfileServiceImpl extends ServiceImpl<WorkfileMapper, Workfile> implements IWorkfileService {
    @Autowired
    FileUploadUtil fileUploadUtil;
    @Autowired
    IWorkService iWorkService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private CheckRoleUtil checkRoleUtil;

    /**
     * 添加文件
     * @param workfile 文件对象
     * @return 操作结果
     */
    @Override
    public boolean addWorkfile(Workfile workfile) {
        Work work = iWorkService.getById(workfile.getWorkid());
        checkRoleUtil.checkPermissionProject(work.getStatus());

        workfile.setFiledate(LocalDateTime.now());
        workfile.setFiledate(LocalDateTime.now());
        workfile.setFlag(1);
        if(baseMapper.insert(workfile) != 1)
            throw new BaseException("上传失败,请重新尝试");
        return true;
    }


    @Override
    public List<Workfile> pageWorkfile(String id) {
        if(StrUtil.isBlank(id)){
            throw new BaseException("著作编号为空值");
        }
        List<Workfile> workfileList = baseMapper.selectList(Wrappers.lambdaQuery(Workfile.class)
                .eq(Workfile::getWorkid,id));
        return workfileList;
    }

    @Override
    public boolean deletWorkfile(String id) throws IOException {
        Workfile one = super.getOne(Wrappers.lambdaQuery(Workfile.class)
                .eq(Workfile::getFileid, id));
        if (Objects.isNull(one)){
            throw new BaseException("文件编号有误!");
        }

        Work work = iWorkService.getById(one.getWorkid());
        checkRoleUtil.checkPermissionProject(work.getStatus());


        boolean delete = fileUploadUtil.delete(one.getFileurl());
        if(!delete){
            throw new BindException("附件删除失败");
        }
        return baseMapper.deleteById(id) == 1;
    }


}

